﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CMD.BAL.MISC;
using CMD_DKT.BAL;
using System.Windows.Threading;
using CMD_DKT.Utilities;
using CMD_DKT.Synchronization;
using System.Reflection;
using System.Diagnostics;
using System.Data;

namespace CMD_DKT.Conf
{
    /// <summary>
    /// Lógica de interacción para WndConfig.xaml
    /// </summary>
    public partial class WndConfig : Window
    {
        public WndConfig()
        {
            InitializeComponent();
            SincronizaCatalogos o = new SincronizaCatalogos();
            txtVersionCatalogos.Text = o.SelectVersion().Rows[0]["Version"].ToString();
            txtUltimaSincCat.Text = o.SelectVersion().Rows[0]["Fecha"].ToString();

            Assembly assembly = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
            lbl_actualVer.Text = fvi.ProductVersion.ToString();

            updateSolInfo();

            getLastStatusReviewDate();
            brdNav_gral_MouseUp(brdNav_gral, null);
        }

        private void spBtnCerrar_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void brdNav_gral_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.showElement("test001");
            this.selectNavItem(((Border)sender).Name);
            //((TextBlock)this.FindName("txtOptionCurrent")).Text="General";
        }

        private void brdNav_sinc_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.showElement("test002");
            this.selectNavItem(((Border)sender).Name);
            //((TextBlock)this.FindName("txtOptionCurrent")).Text = "Sincronización";
        }

        private void brdNav_update_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.showElement("test003");
            this.selectNavItem(((Border)sender).Name);
            //((TextBlock)this.FindName("txtOptionCurrent")).Text = "Actualización de Sistema";
        }

        #region ui_custom_func
        private void showElement(string elem)
        {
            Grid grd = (Grid)this.FindName("grdConfOptions");
            foreach (var test in grd.Children)
            {
                if (((Border)test).Name == elem)
                {
                    ((Border)test).Visibility = Visibility.Visible;
                }
                else
                {
                    ((Border)test).Visibility = Visibility.Hidden;
                }

            }
        }

        private void selectNavItem(string navItem)
        {
            foreach (var border in ((StackPanel)this.FindName("spConfigNav")).Children)
            {
                if (((Border)border).Name == navItem)
                {
                    ((Border)border).BorderThickness = new Thickness(5, 0, 0, 0);
                    ((Border)border).BorderBrush = Brushes.Red;

                    BrushConverter bc = new BrushConverter();
                    Brush b;
                    b = (Brush)bc.ConvertFrom("#f9f9f9");
                    ((Border)border).Background = b;
                    //<Setter Property="Background" Value="#f9f9f9"></Setter>
                }
                else
                {
                    ((Border)border).BorderThickness = new Thickness(0, 0, 0, 0);
                    ((Border)border).Background = Brushes.Transparent;
                    ((Border)border).Style = (Style)this.FindResource("ConfNavBorder");
                }
            }
        }

        private void updateSolInfo()
        {

            StackPanel sp = (StackPanel)this.spSync;
            TextBlock tbSolPendientes = (TextBlock)sp.FindName("tb_solPendientes");
            TextBlock tbDocPendientes = (TextBlock)sp.FindName("tb_docsPendientes");

            int solPendientes = 0;
            int docsPendientes = 0;

            try
            {
                // solicitudes
                DataTable dt = Solicitud.GetSolToSyncFiles();
                int.TryParse(dt.Rows.Count.ToString(),out solPendientes);                
                tbSolPendientes.Text = solPendientes.ToString();

                // documentos
                foreach (DataRow row in dt.Rows)
	            {
		           long unidSol= 0;
                   if (long.TryParse(row["UNID_SOLICITUD"].ToString(), out unidSol))
                   {
                       docsPendientes += Solicitud.GetDataToInsertSolDoc(unidSol).Select("doctos_sync <> 1").Count();
                   }
	            }//foreach

                tbDocPendientes.Text = docsPendientes.ToString();

            }catch(Exception ex)
            {
                tbSolPendientes.Text = "0";
                tbDocPendientes.Text = "0";
            }
        }

        private void getLastStatusReviewDate()
        {

            // TODO: MODIFICAR
            // en vez de buscar en la bd local,llamar servicio web para que consulte en el servidor
            StackPanel sp = (StackPanel)this.spStatus;
            TextBlock tbFechaRevision= (TextBlock)sp.FindName("tb_fechaRevision");
            
            try
            {
                //tbFechaRevision.Text = Solicitud.WFGetLastStatusReviewDate();
                tbFechaRevision.Text = Solicitud.StatReviewGetLastDate();
            }
            catch (Exception ex)
            {
                tbFechaRevision.Text = "12/12/12 12:00:00";
            }
        }

        #endregion ui_custom_func

        private void btnSincCat_Click(object sender, RoutedEventArgs e)
        {
            //---------- INI BZG - Sincroniza Catalogos ------------

            WndSincCatalogos conf = new WndSincCatalogos(this);
            conf.ShowDialog();
            //txtUltimaSincCat.Text = System.DateTime.Now.ToShortDateString();

            SincronizaCatalogos o = new SincronizaCatalogos();
            txtVersionCatalogos.Text = o.SelectVersion().Rows[0]["Version"].ToString();
            txtUltimaSincCat.Text = o.SelectVersion().Rows[0]["Fecha"].ToString();
            //SincronizaCatalogos sinc = new SincronizaCatalogos();
            
            //string compartida = System.Configuration.ConfigurationManager.AppSettings["ServerDocsFolder"];
            //string appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            //string tmpFile = appData + System.Configuration.ConfigurationManager.AppSettings["CarpetaTemporal"];

            //sinc.obtenerArchivos(compartida,tmpFile);
           
            //---------- FIN BZG - Sincroniza Catalogos ------------
        }

        private void btnEnviaSol_Click(object sender, RoutedEventArgs e)
        {

            System.Windows.Media.Animation.Storyboard sb = (System.Windows.Media.Animation.Storyboard)Application.Current.Windows[0].FindResource("rotateImg");
            //Border br = (Border)Application.Current.Windows[0].FindName("brdBrnSinc");

            //sb.Begin(br);

            MainWindow mw = (MainWindow)App.Current.MainWindow;

            Sync.start(sb, mw);

        }

        private void btn_updateVersion_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("¿Desea actualizar la aplicación en este momento?", "Actualización de versión", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                System.Diagnostics.Process.Start(AppConfs.CarpetaInstalacion +  AppConfs.UpdaterProcess);

            }

        }

        private void brdNav_status_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.showElement("test004");
            this.selectNavItem(((Border)sender).Name);
        }

        public void btnRevisarStatus_Click(object sender, RoutedEventArgs e)
        {
            StatusReview.start(tb_fechaRevision);
            MainWindow mw = (MainWindow)App.Current.MainWindow;
            if(mw.Despliega1!=null)
                mw.Despliega1.RefreshContadores();
        }

    }//clase
}
